package com.example.lib_base.base

import android.os.Bundle
import android.os.PersistableBundle
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import java.lang.reflect.ParameterizedType

abstract class BaseActivity<VDB:ViewDataBinding,VM:BaseViewModel>:AppCompatActivity() {
    private val type by lazy {
        (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
    }
    protected val binding:VDB by lazy {
        val clazz=type[0] as Class<VDB>
        val method=clazz.getMethod("inflate",LayoutInflater::class.java)
        method.invoke(null,layoutInflater) as VDB
    }
    protected val viewModel:VM by lazy {
        val clazz=type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }
    open fun onError(t:Throwable){
        //ToastUtils.showLong(t.message)
        Log.e("error","ERROR:${t.message}")
        t.printStackTrace()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        viewModel.onFailed.observe(this,::onError)
        initView()
        initData()
    }

    abstract fun initView()

    abstract fun initData()
}